package com.bnz.service.impl;

import com.alibaba.fastjson.JSON;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //1. 查询所有学生
    @Override
    public List<Student> findAll() {
        //1.1 从redis中查询学生列表
        String studentsJSON = redisTemplate.opsForValue().get("students");
        //1.2 转换为Java对象
        List<Student> studentList = JSON.parseArray(studentsJSON, Student.class);
        //1.3 判断是否存在此列表，如果没有，就从数据库中查询，否则，就直接返回
        if (studentList == null || studentList.size() == 0){
            System.out.println("正在数据库中查询。。。");
            //1.3.1 查询数据库中所有学生
            studentList = studentMapper.selectAll();
            //1.3.2 放到redis中
            redisTemplate.opsForValue().set("students", JSON.toJSONString(studentList));
        }
        //1.4 返回
        return studentList;
    }
}
